package com.lagou.edu.util;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class RegisterChecker {
    private Map<String, Map<String, Integer>> registerRequestsStatics = new ConcurrentHashMap<>();

    private static final String FMT_MINUTE = "yyyyMMddHHmm";

    public synchronized Boolean checkFrequency(String clientIP, int limitMinutes, int limitCount) {
        Map<String, Integer> clientStaticsMap = registerRequestsStatics.get(clientIP);
        String currentMinuteStr = getCurrentMinuteAsString();

        if (clientStaticsMap == null) {
            Map<String, Integer> staticsMap = new HashMap<>();
            staticsMap.put(currentMinuteStr, 1);
            registerRequestsStatics.put(clientIP, staticsMap);
            return limitCount < 1;
        }

        Integer reqCount = clientStaticsMap.get(currentMinuteStr);
        if (reqCount == null) {
            clientStaticsMap.put(currentMinuteStr, 1);
        }
        else {
            reqCount = reqCount + 1;
            clientStaticsMap.put(currentMinuteStr, reqCount);
        }

        int countReq = 0;
        for (int i = 0; i < limitMinutes; i++) {
            String minuteStr = getLastNMinuteAsString(i);

            Integer count = clientStaticsMap.get(minuteStr);
            if (count != null) {
                countReq += count;
            }
        }

        return countReq > limitCount;
    }

    private  String getCurrentMinuteAsString() {
        SimpleDateFormat sdf = new SimpleDateFormat(FMT_MINUTE);
        Date now = new Date();
        return sdf.format(now);
    }

    private String getLastNMinuteAsString(int n) {
        SimpleDateFormat sdf = new SimpleDateFormat(FMT_MINUTE);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -n);
        Date beforeTime = calendar.getTime();
        return sdf.format(beforeTime);
    }
}
